package com.tt;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

import com.tt.listener.OnInitEngineListener;
import com.tt.listener.OnRecordListener;
import com.tt.setting.EngineSetting;
import com.tt.setting.RecordSetting;
import com.tt.util.AiUtil;
import com.tt.util.HandlerUtils;
import com.tt.util.MyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by castiel on 2017/12/29.
 */

public class SkEgnManager {

    private static final String TAG = "17kouyu";

//    private String serverType;
    public static final String SERVER_TYPE_CLOUD = "cloud";
    public static final String SERVER_TYPE_NATIVE = "native";

    public static final int CODE_CREATE_ENGINE_FAIL = 0;
    public static final int CODE_SKEGN_START_FAIL = -1;

    public static final int CODE_START_INIT_ENGINE = 1;
    public static final int CODE_INIT_ENGINE_SUCCESS = 2;
    public static final int CODE_INIT_ENGINE_FAILED = 3;

    public static final int CODE_RECORD_START = 5;
    public static final int CODE_RECORD_RECORDING = 6;
    public static final int CODE_RECORD_END = 7;

    public enum engine_status{
        IDLE,
        RECORDING,
        STOP
    };
    engine_status status1 = engine_status.IDLE;

    private Context mContext;
    private static SkEgnManager mSkEgnManager;

    public static long engine = 0;
    private String mCurrentEngine;//当前引擎

    private boolean isObtainProvisionSuccess;//是否已成功获取证书文件
    private String mSerialNumber = "";
    private File provisionFile = null;

    private STRecorder recorder = null;
    private JSONObject params = null;//评测上传参数

    private Handler mHandler;
    private OnInitEngineListener mOnInitEngineListener;
    private OnRecordListener mOnRecordListener;


    private SkEgnManager(Context context) {
        mContext = context;
    }

    public static SkEgnManager getInstance(Context context) {
        return mSkEgnManager == null ? mSkEgnManager = new SkEgnManager(context) : mSkEgnManager;
    }


    private JSONObject vadObj;
    private SkEgn.skegn_callback callback = new SkEgn.skegn_callback() {
        public int run(byte[] id, int type, byte[] data, int size) {
            if (type == SkEgn.SKEGN_MESSAGE_TYPE_JSON) {
                String result = new String(data, 0, size).trim();
                if(mHandler != null){
                    if(result != null && result.contains("vad_status")){
                        try {
                            vadObj = new JSONObject(result);
                            Message msg = new Message();
                            msg.what = CODE_RECORD_RECORDING;
                            Bundle bundle = new Bundle();
                            bundle.putInt("vad_status", vadObj.getInt("vad_status"));
                            bundle.putInt("sound_intensity", vadObj.getInt("sound_intensity"));
                            msg.setData(bundle);//mes利用Bundle传递数据
                            mHandler.sendMessage(msg);//用activity中的handler发送消息
                            Log.e(TAG, "vad_status===>" + vadObj.getInt("vad_status") + "; sound_intensity===>" + vadObj.getInt("sound_intensity"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else{
                        Message msg = new Message();
                        msg.what = CODE_RECORD_END;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                }
            }
            return 0;
        }
    };

    private void getHandlerOnMainThread(){
         mHandler = HandlerUtils.getInstance().getUIHandlerCB(new HandlerUtils.HandlerDispose() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SkEgnManager.CODE_START_INIT_ENGINE:
                        //开始初始化引擎
                        if(mOnInitEngineListener != null){
                            mOnInitEngineListener.onStartInitEngine();
                        }
                        break;
                    case SkEgnManager.CODE_INIT_ENGINE_SUCCESS:
                        //初始化引擎成功
                        if(mOnInitEngineListener != null){
                            mOnInitEngineListener.onInitEngineSuccess();
                        }
                        break;
                    case SkEgnManager.CODE_INIT_ENGINE_FAILED:
                        //初始化引擎失败
                        if(mOnInitEngineListener != null){
                            mOnInitEngineListener.onInitEngineFailed();
                        }
                        break;
                    case SkEgnManager.CODE_RECORD_START:
                        Log.e(TAG, "SkEgnManager.CODE_RECORD_START");
                        //开始录制
                        if(mOnRecordListener != null){
                            mOnRecordListener.onRecordStart();
                        }
                        break;
                    case SkEgnManager.CODE_RECORD_RECORDING:
                        Log.e(TAG, "SkEgnManager.CODE_RECORD_RECORDING");
                        //录制中
                        Bundle bundle = msg.getData();
                        if(bundle != null){
                            int vad_status = bundle.getInt("vad_status");
                            int sound_intensity = bundle.getInt("sound_intensity");
                            if(mOnRecordListener != null){
                                mOnRecordListener.onRecording(vad_status, sound_intensity);
                            }
                        }
                        break;
                    case SkEgnManager.CODE_RECORD_END:
                        Log.e(TAG, "SkEgnManager.CODE_RECORD_END");
                        //录制结束
                        if(mOnRecordListener != null){
                            mOnRecordListener.onRecordEnd((String)msg.obj);
                        }
                        break;
                }
            }
        });
    }

    //初始化在线版引擎,默认使用本地证书，VAD打开(SDK支持的情况下)，sdkLog关闭，初始化引擎监听关闭
    public void initCloudEngine(String appkey, String secretkey, String userId){
        if(!checkAppKeyAndSecretKey(appkey, secretkey)){
            return;
        }
        getHandlerOnMainThread();
        Log.e(TAG, "mHandler===>" + mHandler);

//        serverType = SERVER_TYPE_CLOUD;
        if(mCurrentEngine != null){
            SkEgn.skegn_delete(engine);
            engine = CODE_CREATE_ENGINE_FAIL;
            status1 = engine_status.STOP;
            mCurrentEngine = null;
        }
        EngineSetting.getInstance(mContext).setUserId(userId);

        /* 初始化cfg */
        EngineSetting setting = EngineSetting.getInstance(mContext).getDefaultCloudInstance();
        JSONObject cfg = new JSONObject();
        try {
            //provision
            File defaultProvisionFile = setting.getDefaultProvisionFile();
            if(defaultProvisionFile != null){
                cfg.put("provision", defaultProvisionFile.getAbsolutePath());
            }else{
                Log.e(TAG, "证书文件不存在");
                return;
            }

            cfg.put("appKey", appkey);
            cfg.put("secretKey", secretkey);

            //vad
            JSONObject vadObj = new JSONObject();
            vadObj.put("enable", setting.isVADEnabled()? 1 : 0);
            vadObj.put("seek", setting.getVadSeek());
            cfg.put("vad", vadObj);

            //sdkLog
            JSONObject sdkLogObj = new JSONObject();
            sdkLogObj.put("enable", setting.isSDKLogEnabled()? 1 : 0);
            sdkLogObj.put("output", AiUtil.externalFilesDir(mContext) + "/sdklog.txt");
            cfg.put("sdkLog", sdkLogObj);

            //cloud
            JSONObject cloudObj = new JSONObject();
            cloudObj.put("server", setting.getServerAddress());
            cloudObj.put("connectTimeout", setting.getConnectTimeout());
            cloudObj.put("serverTimeout", setting.getServerTimeout());
            if(!AppConfig.CLOUD_SERVER_ADDRESS.equals(setting.getServerAddress())){
                cloudObj.put("serverList", "");
            }
            cfg.put("cloud", cloudObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "初始化参数cfg===>" + cfg.toString());

        mCurrentEngine = SERVER_TYPE_CLOUD;
        engine = SkEgn.skegn_new(cfg.toString(), mContext);
        if(engine != CODE_CREATE_ENGINE_FAIL){
            //初始化引擎成功
            Log.e(TAG, "初始化引擎成功");
        } else {
            //初始化引擎失败
            Log.e(TAG, "初始化引擎失败");
        }
    }

    //初始化在线版引擎（自定义初始化设置）
    public void initCloudEngine(String appkey, String secretkey, String userId, EngineSetting setting){
        if(!checkAppKeyAndSecretKey(appkey, secretkey)){
            return;
        }
        getHandlerOnMainThread();
        Log.e(TAG, "mHandler===>" + mHandler);

        if(setting == null){
            //使用默认在线版引擎配置
            initCloudEngine(appkey, secretkey, userId);
        }else{
//            serverType = SERVER_TYPE_CLOUD;
            if(mCurrentEngine != null){
                SkEgn.skegn_delete(engine);
                engine = CODE_CREATE_ENGINE_FAIL;
                status1 = engine_status.STOP;
                mCurrentEngine = null;
            }
            EngineSetting.getInstance(mContext).setUserId(userId);
            //TODO
            //是否需要获取在线证书
            //如果需要，则先获取在线证书
            //如果不需要，则下一步
            if(setting.isUseOnlineProvision()){
                isObtainProvisionSuccess = mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).getBoolean("isObtainProvisionSuccess", false);
                //证书文件校验，存在本地证书文件则使用本地，否则使用线上生成证书
                checkProvisionFile(appkey, secretkey, setting.isNeedUpdateOnlineProvision());
            }else{
                provisionFile = setting.getDefaultProvisionFile();
            }

            mOnInitEngineListener = setting.getOnInitEngineListener();
            mHandler.sendEmptyMessage(CODE_START_INIT_ENGINE);

            /* 初始化cfg */
            JSONObject cfg = new JSONObject();
            try {
                //provision
                if(provisionFile != null && provisionFile.exists()){
                    cfg.put("provision", provisionFile.getAbsolutePath());
                }else{
                    Log.e(TAG, "证书文件不存在");
                    return;
                }

                cfg.put("appKey", appkey);
                cfg.put("secretKey", secretkey);

                //vad
                JSONObject vadObj = new JSONObject();
                vadObj.put("enable", setting.isVADEnabled()? 1 : 0);
                vadObj.put("seek", setting.getVadSeek());
                cfg.put("vad", vadObj);

                //sdkLog
                JSONObject sdkLogObj = new JSONObject();
                sdkLogObj.put("enable", setting.isSDKLogEnabled()? 1 : 0);
                sdkLogObj.put("output", AiUtil.externalFilesDir(mContext) + "/sdklog.txt");
                cfg.put("sdkLog", sdkLogObj);

                //cloud
                JSONObject cloudObj = new JSONObject();
                cloudObj.put("server", setting.getServerAddress());
                cloudObj.put("connectTimeout", setting.getConnectTimeout());
                cloudObj.put("serverTimeout", setting.getServerTimeout());
                if(!AppConfig.CLOUD_SERVER_ADDRESS.equals(setting.getServerAddress())){
                    cloudObj.put("serverList", "");
                }
                cfg.put("cloud", cloudObj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "初始化参数cfg===>" + cfg.toString());
            mCurrentEngine = SERVER_TYPE_CLOUD;
            engine = SkEgn.skegn_new(cfg.toString(), mContext);

            if(engine != CODE_CREATE_ENGINE_FAIL){
                //初始化引擎成功
                Log.e(TAG, "初始化引擎成功");
                if(setting.isUseOnlineProvision()){
                    mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putBoolean("isObtainProvisionSuccess", true).commit();
                    if(setting.isNeedUpdateOnlineProvision()){
                        mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putBoolean("isFirst", false).commit();
                    }
                }
                mHandler.sendEmptyMessage(CODE_INIT_ENGINE_SUCCESS);
            } else {
                //初始化引擎失败
                Log.e(TAG, "初始化引擎失败");
                mHandler.sendEmptyMessage(CODE_INIT_ENGINE_FAILED);
            }
        }
    }

    //初始化离线版引擎,默认使用本地证书，VAD打开(SDK支持的情况下)，sdkLog关闭，初始化引擎监听关闭
    public void initNativeEngine(String appkey, String secretkey, String userId){
        if(!checkAppKeyAndSecretKey(appkey, secretkey)){
            return;
        }
        getHandlerOnMainThread();
        Log.e(TAG, "mHandler===>" + mHandler);

//        serverType = SERVER_TYPE_NATIVE;
        if(mCurrentEngine != null){
            SkEgn.skegn_delete(engine);
            engine = CODE_CREATE_ENGINE_FAIL;
            status1 = engine_status.STOP;
            mCurrentEngine = null;
        }
        EngineSetting.getInstance(mContext).setUserId(userId);

        getSerialNumber(appkey, secretkey);
        /* 初始化cfg */
        EngineSetting setting = EngineSetting.getInstance(mContext).getDefaultNativeInstance();
        JSONObject cfg = new JSONObject();
        try {
            //provision
            File defaultProvisionFile = setting.getDefaultProvisionFile();
            if(defaultProvisionFile != null){
                cfg.put("provision", defaultProvisionFile.getAbsolutePath());
            }else{
                Log.e(TAG, "证书文件不存在");
                return;
            }

            cfg.put("appKey", appkey);
            cfg.put("secretKey", secretkey);

            //vad
            JSONObject vadObj = new JSONObject();
            vadObj.put("enable", setting.isVADEnabled()? 1 : 0);
            vadObj.put("seek", setting.getVadSeek());
            cfg.put("vad", vadObj);

            //sdkLog
            JSONObject sdkLogObj = new JSONObject();
            sdkLogObj.put("enable", setting.isSDKLogEnabled()? 1 : 0);
            sdkLogObj.put("output", AiUtil.externalFilesDir(mContext) + "/sdklog.txt");
            cfg.put("sdkLog", sdkLogObj);

            //provision
            cfg.put("provision", setting.getDefaultProvisionFile().getAbsolutePath());
            //离线资源
            cfg.put("native", setting.getNativeResourcePath());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "初始化参数cfg===>" + cfg.toString());
        mCurrentEngine = SERVER_TYPE_NATIVE;
        engine = SkEgn.skegn_new(cfg.toString(), mContext);
        if(engine != CODE_CREATE_ENGINE_FAIL){
            //初始化引擎成功
            Log.e(TAG, "初始化引擎成功");
        } else {
            //初始化引擎失败
            Log.e(TAG, "初始化引擎失败");
        }
    }

    //初始化离线版引擎（自定义初始化设置）
    public void initNativeEngine(String appkey, String secretkey, String userId, EngineSetting setting){
        if(!checkAppKeyAndSecretKey(appkey, secretkey)){
            return;
        }
        getHandlerOnMainThread();
        Log.e(TAG, "mHandler===>" + mHandler);

        if(setting == null){
            //使用默认离线版引擎配置
            initNativeEngine(appkey, secretkey, userId);
        }else{
//            serverType = SERVER_TYPE_NATIVE;
            if(mCurrentEngine != null){
                SkEgn.skegn_delete(engine);
                engine = CODE_CREATE_ENGINE_FAIL;
                status1 = engine_status.STOP;
                mCurrentEngine = null;
            }
            EngineSetting.getInstance(mContext).setUserId(userId);
            //TODO
            //是否需要获取在线证书
            //如果需要，则先获取在线证书
            //如果不需要，则下一步
            if(setting.isUseOnlineProvision()){
                isObtainProvisionSuccess = mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).getBoolean("isObtainProvisionSuccess", false);
                //证书文件校验，存在本地证书文件则使用本地，否则使用线上生成证书
                checkProvisionFile(appkey, secretkey, setting.isNeedUpdateOnlineProvision());
            }else{
                provisionFile = setting.getDefaultProvisionFile();
                getSerialNumber(appkey, secretkey);
            }

            mOnInitEngineListener = setting.getOnInitEngineListener();
            mHandler.sendEmptyMessage(CODE_START_INIT_ENGINE);

            /* 初始化cfg */
            JSONObject cfg = new JSONObject();
            try {
                //provision
                if(provisionFile != null && provisionFile.exists()){
                    cfg.put("provision", provisionFile.getAbsolutePath());
                }else{
                    Log.e(TAG, "证书文件不存在");
                    return;
                }

                cfg.put("appKey", appkey);
                cfg.put("secretKey", secretkey);
                //vad
                JSONObject vadObj = new JSONObject();
                vadObj.put("enable", setting.isVADEnabled()? 1 : 0);
                vadObj.put("seek", setting.getVadSeek());
                cfg.put("vad", vadObj);

                //sdkLog
                JSONObject sdkLogObj = new JSONObject();
                sdkLogObj.put("enable", setting.isSDKLogEnabled()? 1 : 0);
                sdkLogObj.put("output", AiUtil.externalFilesDir(mContext) + "/sdklog.txt");
                cfg.put("sdkLog", sdkLogObj);

                //离线资源
                cfg.put("native", setting.getNativeResourcePath());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "初始化参数cfg===>" + cfg.toString());
            mCurrentEngine = SERVER_TYPE_NATIVE;
            engine = SkEgn.skegn_new(cfg.toString(), mContext);

            if(engine != CODE_CREATE_ENGINE_FAIL){
                //初始化引擎成功
                if(setting.isUseOnlineProvision()){
                    mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putBoolean("isObtainProvisionSuccess", true).commit();
                    if(setting.isNeedUpdateOnlineProvision()){
                        mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putBoolean("isFirst", false).commit();
                    }
                }
                //初始化引擎成功
                Log.e(TAG, "初始化引擎成功");
                mHandler.sendEmptyMessage(CODE_INIT_ENGINE_SUCCESS);
            } else {
                //初始化引擎失败
                Log.e(TAG, "初始化引擎成功");
                mHandler.sendEmptyMessage(CODE_INIT_ENGINE_FAILED);
            }
        }
    }

    //开始录制（默认）
    public void startRecord(String coreType, String refText, int qType, OnRecordListener onRecordListener){
        if(recorder == null){
            recorder = STRecorder.getInstance();
        }
        mOnRecordListener  = onRecordListener;
        //初始化评测上传参数
        initParams(coreType, refText, qType);
        byte[] id = new byte[64];
        int rv = SkEgn.skegn_start(engine, params.toString(), id, callback, mContext);
        if(rv == CODE_SKEGN_START_FAIL){
            Log.e(TAG, "skegn_start failed");
            stopRecord();
            return;
        }
        status1 = engine_status.RECORDING;
        String wavPath = AiUtil.getFilesDir(mContext).getPath() + "/record/" + new String(id).trim() + ".wav";
        //开始录制
        if(mHandler != null){
            mHandler.sendEmptyMessage(CODE_RECORD_START);
        }
        recorder.start(wavPath, new STRecorder.Callback() {
            public void run(byte[] data, int size) {
                SkEgn.skegn_feed(engine, data, size);
            }
        });
    }

    //开始录制（自定义录音设置）
    public void startRecord(RecordSetting setting, OnRecordListener onRecordListener){
        if(setting == null){
            Log.e(TAG, "RecordSetting instance is required!");
            return;
        }
        if(recorder == null){
            recorder = STRecorder.getInstance();
        }
        mOnRecordListener = onRecordListener;
        //初始化评测上传参数
        initParams(setting);
        byte[] id = new byte[64];
        int rv = SkEgn.skegn_start(engine, params.toString(), id, callback, mContext);
        if(rv == CODE_SKEGN_START_FAIL){
            Log.e(TAG, "skegn_start failed");
            stopRecord();
            return;
        }
        status1 = engine_status.RECORDING;
        String wavPath = AiUtil.getFilesDir(mContext).getPath() + "/record/" + new String(id).trim() + ".wav";
        //开始录制
        if(mHandler != null){
            mHandler.sendEmptyMessage(CODE_RECORD_START);
        }
        recorder.start(wavPath, new STRecorder.Callback() {
            public void run(byte[] data, int size) {
                SkEgn.skegn_feed(engine, data, size);
            }
        });
    }

    //停止录制
    public void stopRecord(){
        if(recorder != null){
            recorder.stop();
        }
        status1 = engine_status.STOP;
    }

    private long start = 0;
    private long end = 0;

    //引擎回收
    public void recycle(){
        start = System.currentTimeMillis();
        Log.e("17kouyu", "start===>" + start);
        mCurrentEngine = null;
        provisionFile = null;
        if (engine != CODE_CREATE_ENGINE_FAIL) {
            Log.e("17kouyu", "start delete");
            SkEgn.skegn_delete(engine);
            Log.e("17kouyu", "end delete");
            engine = CODE_CREATE_ENGINE_FAIL;
            status1 = engine_status.STOP;
        }
        if (recorder != null) {
            Log.e("17kouyu", "start to stop record");
            recorder.stop();
            recorder = null;
            Log.e("17kouyu", "stop record success");
        }
        end = System.currentTimeMillis();
        Log.e("17kouyu", "duration===>" + (end-start));
    }

    //回放
    public void playback(){
        if(recorder != null){
            recorder.playback();
        }
    }

    private boolean checkAppKeyAndSecretKey(String appkey, String secretkey){
        if(appkey==null || "".equals(appkey)){
            Log.e(TAG, "appkey is required!");
            return false;
        }
        if(secretkey==null || "".equals(secretkey)){
            Log.e(TAG, "secretkey is required!");
            return false;
        }
        return true;
    }


    private void checkProvisionFile(String appkey, String secretkey, boolean isNeedUpdateOnlineProvision) {
//        File[] files = mContext.getFilesDir().listFiles();
        File[] files = mContext.getExternalFilesDir(null).listFiles();
        //是否需要更新证书
        if(isNeedUpdateOnlineProvision){
            //需要，判断是否是第一次执行
            boolean isFirst = mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).getBoolean("isFirst", true);
            if(isFirst){
                //更新在线证书,先删除手机本地已保存的证书再重新获取
                for(File file : files){
                    if(AppConfig.PROVISION.equals(file.getName())){
                        file.delete();
                    }
                }
                //保存新证书
                saveProvision(appkey, secretkey);
            }else{
                for(File file : files){
                    if(AppConfig.PROVISION.equals(file.getName())){
                        provisionFile = file;
                    }
                }
                if(provisionFile == null){
                    isObtainProvisionSuccess = false;
                    //保存新证书
                    saveProvision(appkey, secretkey);
                }
            }
        }else{
            //不需要，判断是否已获取成功
            if(isObtainProvisionSuccess){
                //之前已获取过，就使用该证书
                for(File file : files){
                    if(AppConfig.PROVISION.equals(file.getName())){
                        provisionFile = file;
                    }
                }
                if(provisionFile == null){
                    isObtainProvisionSuccess = false;
                    //保存新证书
                    saveProvision(appkey, secretkey);
                }
            }else{
                //如果本地已存在证书则先删除
                if(MyUtil.isExistsProvisionFileInDD(mContext)){
                    for(File file : files){
                        if(AppConfig.PROVISION.equals(file.getName())){
                            file.delete();
                        }
                    }
                }
                //保存新证书
                saveProvision(appkey, secretkey);
            }
        }
    }

    private void saveProvision(String appkey, String secretkey){
        JSONObject json = new JSONObject();
        try {
            json.put("appKey", appkey);
            json.put("secretKey", secretkey);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "result===>" + MyUtil.getSerialNumber(mContext, json.toString()));

        try {
            JSONObject jsonObject = new JSONObject(MyUtil.getSerialNumber(mContext, json.toString()));
            mSerialNumber = jsonObject.getString("serialNumber");
            String provisionStr = jsonObject.getString("provision");
            //保存序列号
            mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putString("serialNumber", mSerialNumber).commit();

//            provisionFile = new File(mContext.getFilesDir(), "skegn.provision");
            provisionFile = new File(mContext.getExternalFilesDir(null), "skegn.provision");

            FileOutputStream fos = null;
            try {
                byte[] decodeBytes = Base64.decode(provisionStr.getBytes(), Base64.DEFAULT);
                fos = new FileOutputStream(provisionFile);
                fos.write(decodeBytes);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getSerialNumber(String appkey, String secretkey){
        JSONObject json = new JSONObject();
        try {
            json.put("appKey", appkey);
            json.put("secretKey", secretkey);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "result===>" + MyUtil.getSerialNumber(mContext, json.toString()));

        try {
            JSONObject jsonObject = new JSONObject(MyUtil.getSerialNumber(mContext, json.toString()));
            mSerialNumber = jsonObject.getString("serialNumber");
            //保存序列号
            mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).edit().putString("serialNumber", mSerialNumber).commit();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化默认评测上传参数
     * @param coreType
     * @param refText
     * @param qType
     */
    public void initParams(String coreType, String refText, int qType){
        params = new JSONObject();
        RecordSetting setting;
        if(coreType == null || "".equals(coreType)){
            Log.e(TAG, "coreType is required!");
            return;
        }
        if(refText == null){
            refText = "";
        }
        if(CoreType.EN_OPEN_EVAL.equals(coreType)){
            //open题型
            setting = new RecordSetting(refText, qType);
        }else if(CoreType.EN_ALIGN_EVAL.equals(coreType)){
            //音频比对
            setting = new RecordSetting(refText);
        }else{
            //普通题型,非音频比对、非开放题型
            setting = new RecordSetting(coreType, refText);
        }

        try {
            //coreProvideType
            params.put("coreProvideType", mCurrentEngine);
            //app
            JSONObject appObj = new JSONObject();
            appObj.put("userId", EngineSetting.getInstance(mContext).getUserId());
            params.put("app", appObj);
            //audio
            JSONObject audioObj = new JSONObject();
            audioObj.put("audioType", setting.getAudioType());
            audioObj.put("sampleRate", setting.getSampleRate());
            audioObj.put("channel", setting.getChannel());
            audioObj.put("sampleBytes", 2);
            audioObj.put("compress", "speex");
            params.put("audio", audioObj);
            //request
            JSONObject requestObj = new JSONObject();
            requestObj.put("coreType", coreType);
            if(CoreType.EN_OPEN_EVAL.equals(coreType)){
                //open题型
                requestObj.put("qType", qType);
            }
            if(CoreType.EN_ALIGN_EVAL.equals(coreType)){
                //音频比对
                requestObj.put("refAudio", setting.getRefAudio());
            }else{
                requestObj.put("refText", setting.getRefText());
            }
            if(SERVER_TYPE_NATIVE.equals(mCurrentEngine)){
                params.put("serialNumber", mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).getString("serialNumber", ""));
            }
            params.put("request", requestObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "上传参数params===>" + params.toString());
    }

    //自定义
    public void initParams(RecordSetting setting){
        params = new JSONObject();
        if(setting.getCoreType() == null || "".equals(setting.getCoreType())){
            Log.e(TAG, "coreType is required!");
            return;
        }
        try {
            //coreProvideType
            params.put("coreProvideType", mCurrentEngine);
            //app
            JSONObject appObj = new JSONObject();
            appObj.put("userId", EngineSetting.getInstance(mContext).getUserId());
            params.put("app", appObj);
            //audio
            JSONObject audioObj = new JSONObject();
            audioObj.put("audioType", setting.getAudioType());
            audioObj.put("sampleRate", setting.getSampleRate());
            audioObj.put("channel", setting.getChannel());
            audioObj.put("sampleBytes", 2);
            audioObj.put("compress", "speex");
            params.put("audio", audioObj);
            //request
            JSONObject requestObj = new JSONObject();
            requestObj.put("coreType", setting.getCoreType());
            if(CoreType.EN_OPEN_EVAL.equals(setting.getCoreType())){
                //open题型
                requestObj.put("qType", setting.getqType());
                requestObj.put("keywords", setting.getKeywords());
            }
            if(CoreType.EN_ALIGN_EVAL.equals(setting.getCoreType())){
                //音频比对
                requestObj.put("refAudio", setting.getRefAudio());
            }else{
                requestObj.put("refText", setting.getRefText());
            }
            //可选项
            requestObj.put("getParam", setting.isNeedRequestParamsInResult()? 1 : 0);
            requestObj.put("paragraph_need_word_score", setting.isNeedWordScoreInParagraph()? 1 : 0);
            requestObj.put("attachAudioUrl", setting.isNeedAttachAudioUrlInResult()? 1 : 0);
            requestObj.put("phoneme_output", setting.isNeedPhonemeOutputInWord()? 1 : 0);
            requestObj.put("dict_type", setting.getDict_type());
            requestObj.put("scale", setting.getScale());
            requestObj.put("precision", setting.getPrecision());
            requestObj.put("slack", setting.getSlack());
            requestObj.put("agegroup", setting.getAgegroup());
            params.put("request", requestObj);
            if(SERVER_TYPE_NATIVE.equals(mCurrentEngine)){
                params.put("serialNumber", mContext.getSharedPreferences("17kouyu", Context.MODE_PRIVATE).getString("serialNumber", ""));
            }
            //可选项
            params.put("soundIntensityEnable", setting.isNeedSoundIntensity()? 1 : 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "上传参数params===>" + params.toString());
    }

}
